package com.university.evaluation.utils;

import com.university.evaluation.exception.FileUploadException;
import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class FileUtils {

    // 文件存储根路径
    private final String ROOT_PATH = "upload/";

    // 图片存储路径
    private final String IMAGE_PATH = "images/";

    // 文档存储路径
    private final String DOCUMENT_PATH = "documents/";

    // 临时文件存储路径
    private final String TEMP_PATH = "temp/";

    // 上传图片文件
    public String uploadImage(MultipartFile file) {
        return uploadFile(file, IMAGE_PATH);
    }

    // 上传文档文件
    public String uploadDocument(MultipartFile file) {
        return uploadFile(file, DOCUMENT_PATH);
    }

    // 上传临时文件
    public String uploadTempFile(MultipartFile file) {
        return uploadFile(file, TEMP_PATH);
    }

    // 通用文件上传方法
    private String uploadFile(MultipartFile file, String subPath) {
        if (file.isEmpty()) {
            throw new FileUploadException("上传的文件为空");
        }

        try {
            // 获取文件原始名称
            String originalFilename = file.getOriginalFilename();
            // 获取文件扩展名
            String extension = FilenameUtils.getExtension(originalFilename);
            // 生成新的文件名，避免文件名冲突
            String newFilename = generateUniqueFilename(extension);

            // 创建日期目录结构
            String dateDir = new SimpleDateFormat("yyyyMMdd").format(new Date());
            String filePath = ROOT_PATH + subPath + dateDir + "/";

            // 创建目录
            File directory = new File(filePath);
            if (!directory.exists()) {
                directory.mkdirs();
            }

            // 保存文件
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath + newFilename);
            Files.write(path, bytes);

            // 返回文件的相对路径
            return subPath + dateDir + "/" + newFilename;
        } catch (IOException e) {
            throw new FileUploadException("文件上传失败: " + e.getMessage(), e);
        }
    }

    // 生成唯一的文件名
    private String generateUniqueFilename(String extension) {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        return timestamp + "_" + uuid + "." + extension;
    }

    // 删除文件
    public boolean deleteFile(String relativePath) {
        try {
            Path path = Paths.get(ROOT_PATH + relativePath);
            return Files.deleteIfExists(path);
        } catch (IOException e) {
            throw new RuntimeException("文件删除失败: " + e.getMessage(), e);
        }
    }

    // 获取文件的字节数组
    public byte[] getFileBytes(String relativePath) {
        try {
            Path path = Paths.get(ROOT_PATH + relativePath);
            return Files.readAllBytes(path);
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败: " + e.getMessage(), e);
        }
    }

    // 获取文件的MIME类型
    public String getContentType(String relativePath) {
        try {
            Path path = Paths.get(ROOT_PATH + relativePath);
            return Files.probeContentType(path);
        } catch (IOException e) {
            throw new RuntimeException("获取文件类型失败: " + e.getMessage(), e);
        }
    }

    // 验证文件大小
    public void validateFileSize(MultipartFile file, long maxSizeBytes) {
        if (file.getSize() > maxSizeBytes) {
            throw new FileUploadException("文件大小超过限制");
        }
    }

    // 验证文件类型
    public void validateFileType(MultipartFile file, String[] allowedTypes) {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename).toLowerCase();
        boolean isValidType = false;
        for (String type : allowedTypes) {
            if (type.equalsIgnoreCase(extension)) {
                isValidType = true;
                break;
            }
        }
        if (!isValidType) {
            throw new FileUploadException("不支持的文件类型");
        }
    }

}